import argparse
import cv2
import matplotlib.pyplot as plt
import numpy as np
import time
from numba import jit

@jit(nopython=True)
def process_array(img):
    x,y,d = img.shape 
    
    new_img = np.zeros(((x+1)//2,(y+1)//2,3),dtype='u1')
    
    #low efficiency
    for i in range(new_img.shape[0]):
        for j in range(new_img.shape[1]):
            new_img[i,j,0] = int(img[i*2:i*2+2,j*2:j*2+2,0].mean())
            new_img[i,j,1] = int(img[i*2:i*2+2,j*2:j*2+2,1].mean())
            new_img[i,j,2] = int(img[i*2:i*2+2,j*2:j*2+2,2].mean())
        
    return new_img
    
def meanDown(img):
    if not isinstance(img, np.ndarray):
        raise TypeError('目标图片应转换为np.ndarray.')
        
    return process_array(img)
    
def main():
    # 1. 解析命令行参数
    parser = argparse.ArgumentParser(description='Image pyramid and edge detection')
    parser.add_argument('image_path', help='Path to input image (png/jpg/bmp)')
    args = parser.parse_args()

    # 2. 读取图片
    img = cv2.imread(args.image_path)
    if img is None:
        print(f"Error: Could not read image from {args.image_path}")
        return

    # 3. 金字塔降采样
    img_half = cv2.pyrDown(img)
    img_quarter = cv2.pyrDown(img_half)

    # 4. 均值采样
    img_mean_half = meanDown(img)
    img_mean_quarter = meanDown(img_mean_half)
    
    # 5. Canny边缘检测
    t1 = time.time()
    edges_original = cv2.Canny(img, 100, 200)
    edges_half = cv2.Canny(img_half, 100, 200)
    edges_quarter = cv2.Canny(img_quarter, 100, 200)

    # 5. 使用matplotlib显示结果
    plt.figure(figsize=(15, 15))

    # 显示原始尺寸图片
    plt.subplot(3, 3, 1)
    plt.imshow(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))
    plt.title('Original Image')
    plt.axis('off')

    # 显示1/2尺寸图片
    plt.subplot(3, 3, 2)
    plt.imshow(cv2.cvtColor(img_half, cv2.COLOR_BGR2RGB))
    plt.title('1/2 Size Image')
    plt.axis('off')

    # 显示1/4尺寸图片
    plt.subplot(3, 3, 3)
    plt.imshow(cv2.cvtColor(img_quarter, cv2.COLOR_BGR2RGB))
    plt.title('1/4 Size Image')
    plt.axis('off')
    
    # 显示1/2尺寸图片
    plt.subplot(3, 3, 5)
    plt.imshow(cv2.cvtColor(img_mean_half, cv2.COLOR_BGR2RGB))
    plt.title('1/2 Size mean Image')
    plt.axis('off')

    # 显示1/4尺寸图片
    plt.subplot(3, 3, 6)
    plt.imshow(cv2.cvtColor(img_mean_quarter, cv2.COLOR_BGR2RGB))
    plt.title('1/4 Size mean Image')
    plt.axis('off')

    # 显示原始尺寸边缘
    plt.subplot(3, 3, 7)
    plt.imshow(edges_original, cmap='gray')
    plt.title('Original Edges')
    plt.axis('off')

    # 显示1/2尺寸边缘
    plt.subplot(3, 3, 8)
    plt.imshow(edges_half, cmap='gray')
    plt.title('1/2 Size Edges')
    plt.axis('off')

    # 显示1/4尺寸边缘
    plt.subplot(3, 3, 9)
    plt.imshow(edges_quarter, cmap='gray')
    plt.title('1/4 Size Edges')
    plt.axis('off')

    plt.tight_layout()
    plt.show()

if __name__ == "__main__":
    main()
